package com.kim.chapter10.http.xml.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import java.util.List;
import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpUtil.setContentLength;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

public class HttpXmlResponseEncoder extends
        AbstractHttpXmlEncoder<HttpXmlResponse> {

    @Override
    protected void encode(ChannelHandlerContext ctx, HttpXmlResponse msg,
                          List<Object> out) throws Exception {
        ByteBuf body = encode0(ctx, msg.getResult());
        //获取应答消息，对业务消息进行判断
        FullHttpResponse response = msg.getHttpResponse();
        if (response == null) {
            response = new DefaultFullHttpResponse(HTTP_1_1, OK, body);
        } else {
            response = new DefaultFullHttpResponse(
                    msg.getHttpResponse().protocolVersion(),
                    msg.getHttpResponse().status(),
                    body);
        }
        //设置消息体内容格式
        response.headers().set(CONTENT_TYPE, "text/xml");
        //设置消息体长度
        setContentLength(response, body.readableBytes());
        //将应答消息DefaultFullHttpResponse加入到编码结果列表中，由后续Netty的HTTP编码类进行二次编码
        out.add(response);
    }

}
